<template>
	<view>

		<!-- #ifdef MP-WEIXIN -->
		<u-navbar height="90" bgColor="#0081ff">
			<view class="u-nav-slot margin-top-xl" slot="left">
				<u-icon name="list-dot" size="32" color="#ffffff" v-if="!isCheck" @tap="showModal('DrawerModal')">
				</u-icon>
				<u-icon name="close" size="32" color="#ffffff" v-if="isCheck" @tap="finish"></u-icon>
			</view>
			<view class="u-nav-slot margin-top-xl" slot="right">
				<u-icon name="plus-circle" size="32" color="#ffffff" v-if="!isCheck" @tap="addDeviceVisible = true">
				</u-icon>
				<u-icon name="checkmark" size="32" color="#ffffff" v-if="isCheck" @tap="checkAll"></u-icon>
			</view>
		</u-navbar>
		<!-- #endif -->
		<!-- #ifdef H5 ||  APP-PLUS -->
		<u-navbar height="80" bgColor="#0081ff">
			<view class="u-nav-slot" slot="left">
				<u-icon name="list-dot" size="32" color="#ffffff" v-if="!isCheck" @tap="showModal('DrawerModal')">
				</u-icon>
				<u-icon name="close" size="32" color="#ffffff" v-if="isCheck" @tap="finish"></u-icon>
			</view>
			<!-- 加上六盘水炬元物联网标志-->
			<!-- 	<view class="u-nav-slot" slot="center">
				<text style="font-size: 24px;color: #00F5D4;">六盘水炬元物联网</text>
			</view> -->
			<!-- 加上六盘水炬元物联网标志-->
			<view class="u-nav-slot" slot="right">
				<u-icon name="plus-circle" size="32" color="#ffffff" v-if="!isCheck" @tap="addDeviceVisible = true">
				</u-icon>
				<u-icon name="checkmark" size="32" color="#ffffff" v-if="isCheck" @tap="checkAll"></u-icon>
			</view>
		</u-navbar>
		<!-- #endif -->

		<!-- 设备列表 -->
		<scroll-view height="750rpx" scroll-y refresher-enabled="true" :refresher-triggered="triggered"
			:refresher-threshold="50" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
			refresher-background="#f1f1f1" class="page margin-top-xl">

			<checkbox-group class="nav-list">
				<view hover-class="none" @touchstart.prevent="goTouchstart()"
					@touchend.prevent="goTouchend(item.deviceId,item.deviceName,item.shareDevice,item.shareStatus)"
					class="nav-li bg-white" navigateTo :style="[{animation: 'show ' + ((index+1)*0.2+1) + 's 1'}]"
					v-for="(item,index) in elements" :key="index">
					<view style="margin-top: -25rpx;margin-left: -25rpx;" v-if="isCheck">
						<checkbox class='round' :checked="item.checked" :class="item.checked?'checked':''">
						</checkbox>
					</view>
					<view class="nav-title cu-avatar xl round justify-start"
						:style="'background-image:url('+ imgUrl + item.image + ');'">
					</view>
					<view class="text-left  margin-top-xs">
						<view class="text-xl" style="color: #333333;">{{item.deviceName}}</view>
						<view v-if="item.shareDevice" style="font-size: 8px;">共享设备</view>
					</view>
					<text style="font-size: 12px;" class="text-blue" v-if="item.deviceStatus == 1">在线</text>
					<text style="font-size: 12px;" v-else>离线</text>
				</view>
			</checkbox-group>
			<!-- 未登录或设备为空提醒 -->
			<view v-if="token == null || elements.length <= 0">
				<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" text="快来加入IoTLink吧,体验不一样的云控制!">
				</u-empty>
				<view class="margin-xl padding-lg">
					<u-button v-if="token == null" text="您未登录,请登录" size="normal" shape="circle" color="#0081ff" 
					@click="toLogin()">
					</u-button>
					<u-button v-if="token != null" text="添加设备" size="normal" shape="circle" color="#0081ff"
					@click="showModal('deviceModal')">
					</u-button>
				</view>
				<u-modal content="您未登录,请登录后再来操作吧" :show="show" confirmText="去登录" showCancelButton closeOnClickOverlay
					@confirm="toLogin" @cancel="cancel" @close="cancel"></u-modal>
			</view>

			<view class="cu-tabbar-height"></view>
		</scroll-view>
		<!-- 侧边栏 -->
		<view class="cu-modal drawer-modal justify-start" :class="modalName=='DrawerModal'?'show':''" @tap="hideModal">

			<view class="cu-dialog basis-xl" @tap.stop="" :style="[{top:0+'px',height:'calc(100vh)'}]">
				<view class="cu-list menu text-left">
					<view class="bg-white" style="height: 3vh;"> </view>
					<!-- 个人信息 -->
					<view class="cu-item arrow " @tap="toUserInfo()">
						<view class="cu-avatar lg round margin-top-xl  margin-bottom-xl"
							:style="'background-image:url(' + imgUrl + user.image+ ');'">
						</view>
						<view class="content margin-left-sm" style="display: flex;flex-direction: column;">
							<text class="text-xxl">{{user.username}}</text>
							<text class="text-xs">{{user.number}}个设备接入</text>
						</view>
					</view>
					<!-- 设备管理 -->
					<view class="cu-item arrow" @tap="toManage()">
						<view class="cuIcon-list"></view>
						<view class="content margin-left-sm">
							<text class="text-xl">设备管理</text>
						</view>
					</view>
					<!-- 设备共享 -->
					<view class="cu-item arrow" @tap="toShareManage()">
						<view class="cuIcon-friend xl"></view>
						<view class="content margin-left-sm">
							<text class="text-xl">设备共享</text>
						</view>
					</view>
					<!-- 定时任务 -->
					<view class="cu-item arrow" @tap="toTaskManage()">
						<view class="cuIcon-remind xl"></view>
						<view class="content margin-left-sm">
							<text class="text-xl">定时管理</text>
						</view>
					</view>
					<!-- 联动管理 -->
					<view class="cu-item arrow" @tap="toLinkage()">
						<view class="cuIcon-hot xl"></view>
						<view class="content margin-left-sm">
							<text class="text-xl">联动管理</text>
						</view>
					</view>

					<!-- 设备共享 -->
					<view class="cu-item arrow" @tap="toAbout()">
						<view class="cuIcon-tag xl"></view>
						<view class="content margin-left-sm">
							<text class="text-xl">关于</text>
						</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 底部导航 -->
		<view class="cu-bar tabbar bg-gray shadow foot my-foot bg-white" v-if="isCheck">
			<image src="../../static/delete.png" style="width: 100rpx; height: 100rpx;" @tap="remove">
			</image>
		</view>
		<!-- 添加设备模态框 -->
		<u-modal :show="addDeviceVisible" title="添加设备" content='content' showCancelButton
			@cancel="addDeviceVisible = false" @confirm="saveDevice">
			<view class="">
				<u--form>
					<u-form-item borderBottom>
						<u--input v-model="device.deviceName" border="none" inputAlign="center" placeholder="请输入设备名称">
						</u--input>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
		<u-popup :show="popupShow" mode="center" @close="popupClose()" @open="popupOpen()" :closeable="true" :closeOnClickOverlay="false">
			<view class="t-popup">
				<view class="t-title">初识</view>
				<view class="t-center">
					<text>人生若只如初见，何事秋风悲画扇</text></br>
					<text>如果您是第一次使用这个宝藏应用，可以前往关于应用，了解如何快速接入你的设备。实现你的第一个远程控制吧！</text>
				</view>
				<view class="t-checkbox">
					<u-checkbox-group @change="popupCheckbox"  placement="row">
						<u-checkbox label="下次打开应用不再提示!"></u-checkbox>
					</u-checkbox-group>
				</view>
				<u-button type="primary" text="前往" @click="toAbout"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	import APPUpdate, {
		getCurrentNo
	} from '@/uni_modules/zhouWei-APPUpdate/js_sdk/appUpdate'
	// #endif
	export default {
		name: "basics",
		data() {
			return {
				version: "", // 版本号
				imgUrl: this.imgUrl,
				user: {
					userId: null,
					image: null,
					username: '未登录',
					number: 0
				},
				token: uni.getStorageSync("token") || null,
				show: false,
				isCheck: false,
				modalName: null, // 侧边栏模态框显示
				addDeviceVisible: false,
				triggered: false,
				elements: [],
				device: {
					deviceName: null
				},
				checkedList: [],
				popupShow: false,
				popupCheck: true
			};
		},
		onLoad() {
			// #ifdef APP-PLUS
			getCurrentNo(res => {
				this.version = res.version;
			});
			// #endif
			this.getUserInfo()
			this.getDeviceList()
			if(this.elements == null){
				this.popupOpen()
			}
		},
		methods: {
			// 检查APP是否有新版本
			updateApp() {
				APPUpdate(true);
			},
			// 删除设备
			remove() {
				let deviceIds = []
				let list = this.elements
				for (var i = 0; i < list.length; i++) {
					if (list[i].checked) {
						deviceIds.push(list[i].deviceId)
					}
				}
				let _this = this
				uni.showModal({
					content: '【会删除设备下的所有数据】危险操作，是否继续！',
					success: function(res) {
						if (res.confirm) {
							_this.$http.request({
								url: 'app/device/delete',
								method: 'GET',
								data: {
									'deviceIds': deviceIds.toString(),
								},
								success: (data) => {
									if (data.data && data.data.code == 0) {
										_this.getDeviceList()
										_this.isCheck = false
									} else {
										uni.showToast({
											title: data.data.msg,
											icon: 'none',
											duration: 1000
										})
									}
								}
							})
						} else if (res.cancel) {}
					}
				})
			},

			//完成选择
			finish() {
				this.isCheck = false
				let list = this.elements
				for (var i = 0; i < list.length; i++) {
					if (!list[i].shareDevice) {
						list[i].checked = false
					}
				}
				this.elements = list
			},

			// 全选
			checkAll() {
				let list = this.elements
				for (var i = 0; i < list.length; i++) {
					if (!list[i].shareDevice) {
						list[i].checked = !list[i].checked
					}
				}
				this.elements = list
			},

			// 下拉刷新
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				if (!this.triggered) //界面下拉触发，triggered可能不是true，要设为true 
					this.triggered = true;
				setTimeout(() => {
					this.getDeviceList()
					this.triggered = false; //触发onRestore，并关闭刷新图标 
					this._freshing = false;
				}, 2000)
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},

			//获取用户的设备列表
			getDeviceList() {
				let that = this
				this.$http.request({
					url: 'app/device/allDevice',
					method: 'GET',
					success: (data) => {
						if (data.data && data.data.code == 0) {
							let list = data.data.list
							for (var i = 0; i < list.length; i++) {
								list[i].checked = false
							}
							that.elements = list
						}
					}
				})
			},

			//显示模态框
			showModal(type) {
				let that = this
				let token = uni.getStorageSync("token")
				if (type == "deviceModal") {
					if (token == null || token == '') {
						that.show = true
					} else if (token != '' && that.user.userId != null) {
						that.addDeviceVisible = type
					} else {
						uni.showToast({
							title: '网络异常！',
							icon: 'error',
							position: 100
						})
					}

				}
				if (type == "DrawerModal") {
					if (token == null || token == '') {
						that.getUserInfo()
						that.modalName = type
					} else {
						that.getUserInfo()
						that.modalName = type
					}
				}
			},
			toLogin() {
				uni.navigateTo({
					url: '../user/login'
				})
			},
			cancel() {
				this.show = false
			},

			//关闭模态框
			hideModal(e) {
				this.modalName = null
			},

			// 按键长按
			goTouchstart() {
				let _this = this;
				clearTimeout(_this.timeOutEvent);
				_this.timeOutEvent = setTimeout(function() {
					_this.timeOutEvent = 0;
					_this.isCheck = true
				}, 600);
			},

			// 按钮单击 跳转设备按键详情页
			goTouchend(deviceId, deviceName, isShare, shareStatus) {
				let _this = this;
				clearTimeout(_this.timeOutEvent);
				if (_this.timeOutEvent !== 0) {
					if (isShare && !shareStatus) {
						uni.showToast({
							title: "设备维护中，请等待开放共享",
							icon: "none",
							position: 1000
						})
						return;
					}
					if (_this.isCheck) {
						//  处理长按事件...
						if (isShare) { // 判断是共享设备还是自己创建的设备
							uni.showToast({
								title: '没有权限！',
								icon: 'none'
							})
							return
						}
						let index = _this.elements.findIndex(item => item.deviceId == deviceId);
						_this.elements[index].checked = !_this.elements[index].checked

						return
					}
					if (_this.user.status == 1) {
						uni.navigateTo({
							url: '/pages/basics/info?deviceId=' + deviceId + "&deviceName=" + deviceName +
								'&isShare=' + isShare
						})
					} else {
						uni.showToast({
							title: '该用户已被禁止使用，请联系管理员！',
							icon: "none"
						})
					}

				}
			},

			// 获取用户信息
			getUserInfo() {
				this.$http.request({
					url: 'app/user/userInfo',
					method: 'GET',
					success: (data) => {
						if (data.data && data.data.code == 0) {
							if (data.data.user == null) {
								uni.removeStorageSync("token")
								uni.showToast({
									title: '用户不存在，请重新登录！',
									icon: 'none',
									position: 1000
								})
							}
							this.user = data.data.user
						}
						if (data.data.code == 401) {
							uni.showToast({
								title: data.data.msg,
								icon: 'none',
								position: 1000
							})
							uni.setStorageSync("token", null)
						}
					}
				})
			},

			//添加设备
			saveDevice() {
				let token = uni.getStorageSync("token");
				if (token == null || token == '') {
					this.device.deviceName = null
					this.addDeviceVisible = false
					this.show = true
					return
				}
				if (this.device.deviceName == null) {
					this.addDeviceVisible = false
					uni.showToast({
						title: '设备名不能为空！',
						icon: 'none',
						position: 1000
					})
					return
				}
				this.$http.request({
					url: 'app/device/save',
					method: 'POST',
					dataType: 'json',
					data: {
						'deviceName': this.device.deviceName
					},
					success: (data) => {
						if (data.data && data.data.code == 0) {
							this.device.deviceName = null
							this.getDeviceList()
							this.addDeviceVisible = false
						}
					}
				})
			},
			popupOpen() {
				let flag = uni.getStorageSync("popup") || "1"
				if(flag == "1"){
					this.popupShow = true	
				}
			},
			popupClose() {
				let flag = this.popupCheck
				if(flag){
					uni.setStorageSync("popup","1")
				}else{
					uni.setStorageSync("popup","0")
				}
				this.popupShow = false
			},
			popupCheckbox(e){
				this.popupCheck = !this.popupCheck
				console.log(this.popupCheck)
			},
			// 跳转到用户信息
			toUserInfo() {
				if (uni.getStorageSync("token") == null || uni.getStorageSync("token") == '') {
					this.show = true
				} else if (this.user.status == 1) {
					uni.navigateTo({
						url: "/pages/user/userInfo"
					})
				} else {
					uni.showToast({
						title: '该用户已被禁止使用，请联系管理员！',
						icon: "none"
					})
				}

			},

			// 跳转到设备管理
			toManage() {
				if (uni.getStorageSync("token") == null || uni.getStorageSync("token") == '') {
					this.show = true
				} else if (this.user.status == 1) {
					uni.navigateTo({
						url: "/pages/basics/manage"
					})
				} else {
					uni.showToast({
						title: '该用户已被禁止使用，请联系管理员！',
						icon: "none"
					})
				}
			},

			// 跳转到分享
			toShareManage() {
				if (uni.getStorageSync("token") == null || uni.getStorageSync("token") == '') {
					this.show = true
				} else if (this.user.status == 1) {
					uni.navigateTo({
						url: "/pages/share/shareManage"
					})
				} else {
					uni.showToast({
						title: '该用户已被禁止使用，请联系管理员！',
						icon: "none"
					})
				}
			},
			// 跳转到分享
			toTaskManage() {
				if (uni.getStorageSync("token") == null || uni.getStorageSync("token") == '') {
					this.show = true
				} else if (this.user.status == 1) {
					uni.navigateTo({
						url: "/pages/task/taskManage"
					})
				} else {
					uni.showToast({
						title: '该用户已被禁止使用，请联系管理员！',
						icon: "none"
					})
				}
			},
			toLinkage() {
				if (uni.getStorageSync("token") == null || uni.getStorageSync("token") == '') {
					this.show = true
				} else if (this.user.status == 1) {
					uni.navigateTo({
						url: "/pages/linkage/linkage"
					})
				} else {
					uni.showToast({
						title: '该用户已被禁止使用，请联系管理员！',
						icon: "none"
					})
				}
			},

			toAbout() {
				uni.navigateTo({
					url: "/pages/about/about"
				})
			},

		}
	}
</script>

<style>
	.page {
		height: 80vh;
	}

	.top {
		margin-top: 10vh;
	}

	.fixed {
		position: fixed;
		z-index: 99;
	}

	.my-foot {
		height: 10vh;
		display: flex;
		align-content: flex-end;
		justify-content: center;
		align-items: cente
	}
</style>
<style lang="scss" scoped>
	.t-popup {
		width: 600rpx;
		height: 520rpx;
		@include flex;
		padding: 50rpx;
		flex-direction: column;
		align-items: center;

		.t-title {
			font-size: 20px;
			font-weight: 600;
			letter-spacing: 10px;
		}

		.t-center {
			font-size: 15px;
			font-weight: 500;
			margin-top: 20rpx;
		}
		.t-checkbox{
			align-self: start;
			margin-top:10px;
		}
		.u-button {
		margin-top: 10px;
		}
	}
</style>
